/*
* @Author: wangke
* @Date:   2016-06-01 16:59:07
* @Last Modified by:   wangke
* @Last Modified time: 2016-06-02 09:32:12
*/

#include "pthread.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"

#define DELAY	(2)

typedef struct msg {
	pthread_mutex_t mutex;
	pthread_cond_t cond;
	int numA;
	int numB;
}MSG;

static MSG data;

static void *func_add(void *arg)
{
	while(1) {
	    
	    sleep(DELAY*2);
	
	    pthread_mutex_lock(&data.mutex);
	    data.numA++;

	     printf("func add: numA = %d\n", data.numA);

	    if(data.numA%7==0) {
	    	pthread_cond_signal(&data.cond);
	    	printf("func add signal ...\n");
	    }
	    pthread_mutex_unlock(&data.mutex);
	}

}

static void *func_sub(void *arg)
{

	while(1) {
	    ;
	}
}

static void *func_calc(void *arg)
{
	while(1) {
		sleep(DELAY);
		printf("func calc ...\n");
	    pthread_mutex_lock(&data.mutex);

	    data.numA=0;
	    if(data.numA==0) {
	    	printf("pthread wait...\n");
	    	pthread_cond_wait(&data.cond, &data.mutex);
	    }

	    // if(data.numA>1) {
	    // 	data.numA--;
	    // 	if(data.numA==1) {
	    // 		printf("pthread wait...\n");
	    // 		pthread_cond_wait(&data.cond, &data.mutex);
	    // 	}
	    // }

	    printf("[calc] data.numA = %d\n", data.numA);

	    pthread_mutex_unlock(&data.mutex);
	}
}


int main(int argc, char const *argv[])
{
	pthread_t pth_add, pth_sub, pth_calc;
	int ret;

	data.numA = 0;
	data.numB = 13;

	pthread_cond_init(&data.cond, NULL);
	pthread_mutex_init(&data.mutex, NULL);

	pthread_create(&pth_add, NULL, func_add, NULL);
	pthread_create(&pth_sub, NULL, func_sub, NULL);
	pthread_create(&pth_calc, NULL, func_calc, NULL);

	while(1) {
	    ;
	}


	return 0;
}




